'use client';

import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react';
import { PlayInfo } from '@/lib/utils/types';
import { useColumns } from '@/app/hooks/use-columns';
import HtmlLink from '@/app/components/common/html-link';
import { saveEpisodeHistory } from '@/lib/utils/episode-history';

interface PlaylistContainerProps {
  playList: PlayInfo[];
  currentIndex?: number;
  videoId?: number;
  onEpisodeChange?: (index: number) => void;
}

export default function PlaylistContainer({ playList, currentIndex, videoId, onEpisodeChange }: PlaylistContainerProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const activeItemRef = useRef<HTMLAnchorElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const columns = useColumns(containerRef, 1, 4, playList);
  const [localCurrentIndex, setLocalCurrentIndex] = useState(currentIndex ?? 0);
  const [isReversed, setIsReversed] = useState(false);

  // 当props中的currentIndex变化时，更新本地状态
  useEffect(() => {
    setLocalCurrentIndex(currentIndex ?? 0);
  }, [currentIndex]);

  // 首次加载时立即滚动到选中集数
  const isFirstRender = useRef(true);
  useEffect(() => {
    // 只在首次渲染完成和选集列表准备好后执行一次
    if (isFirstRender.current && activeItemRef.current && scrollContainerRef.current && columns > 0) {
      const item = activeItemRef.current;
      const container = scrollContainerRef.current;
      
      // 计算元素相对于容器的位置
      const itemRect = item.getBoundingClientRect();
      const containerRect = container.getBoundingClientRect();
      
      // 增加额外的偏移量来确保元素更居中
      const offsetY = (containerRect.height - itemRect.height) / 2;
      const centerPosition = itemRect.top - containerRect.top - offsetY;
      
      // 直接滚动到位置，不使用平滑效果
      if (Math.abs(centerPosition) > 10) {
        container.scrollTo({
          top: container.scrollTop + centerPosition
        });
        console.log('首次加载立即滚动到选中选集:', localCurrentIndex);
      }
      
      isFirstRender.current = false;
    }
  }, [columns, localCurrentIndex]); // 依赖columns确保布局已计算好

  // 获取排序后的播放列表
  const sortedPlayList = useMemo(() => {
    const sorted = [...playList];
    if (isReversed) {
      return sorted.reverse();
    }
    return sorted;
  }, [playList, isReversed]);

  // 处理选集点击
  const handleEpisodeClick = useCallback((index: number) => {
    // 首先更新本地状态
    setLocalCurrentIndex(index);

    // 通知父组件选集已更改
    onEpisodeChange?.(index);
    
    if (videoId) {
      // 保存选集历史到localStorage
      saveEpisodeHistory(videoId, index);
      
      // 使用 history API 直接修改 URL，不触发页面跳转
      const newUrl = `/detail/${videoId}-${index}.html`;
      window.history.pushState({ path: newUrl }, '', newUrl);
      
      // 派发自定义事件通知播放器切换播放源
      if (typeof window !== 'undefined') {
        const episode = playList[index];
        if (episode && episode.url) {
          console.log('大屏切换选集:', index, episode.url);
          
          // 确保事件详情包含完整信息
          const eventDetail = {
            url: episode.url, 
            name: episode.name,
            index: index
          };
          
          // 使用更明确的事件派发方式
          const event = new CustomEvent('switchEpisode', { 
            detail: eventDetail,
            bubbles: true,
            cancelable: true
          });
          
          // 确保事件成功派发
          const dispatched = window.dispatchEvent(event);
          if (!dispatched) {
            console.error('选集切换事件派发失败');
          }
        } else {
          console.error('选集信息不完整或URL为空:', index, episode);
        }
      }
    }
    
    // 清除当前可能存在的焦点状态
    if (document.activeElement instanceof HTMLElement) {
      document.activeElement.blur();
    }
  }, [onEpisodeChange, videoId, playList]);
  
  // 切换排序方向
  const toggleSort = useCallback(() => {
    // 设置来自排序的标识
    // setIsFromSort(true); - 已删除
    // 设置不进行滚动
    // setShouldScroll(false); - 已删除
    // 改变排序方向
    setIsReversed(prev => !prev);
    
    // 使用requestAnimationFrame等待排序完成后再滚动
    requestAnimationFrame(() => {
      // 滚动到列表顶部
      if (scrollContainerRef.current) {
        try {
          const container = scrollContainerRef.current;
          if (container) {
            container.scrollTo({
              top: 0,
              behavior: 'smooth'
            });
          }
        } catch (err) {
          console.error('滚动到顶部失败:', err);
        }
      }

      // 使用setTimeout确保滚动动画完成后
      // setTimeout(() => {
      //   setShouldScroll(true);
      //   setIsFromSort(false);
      // }, 500);
    });
  }, []);

  // 当localCurrentIndex变化时，滚动到相应的元素
  useEffect(() => {
    if (activeItemRef.current && scrollContainerRef.current) {
      // 增加延迟时间确保DOM和布局完全渲染
      const timer = setTimeout(() => {
        if (activeItemRef.current && scrollContainerRef.current) {
          try {
            // 使用更精确的滚动定位
            const item = activeItemRef.current;
            const container = scrollContainerRef.current;
            
            // 计算元素相对于容器的位置
            const itemRect = item.getBoundingClientRect();
            const containerRect = container.getBoundingClientRect();
            
            // 增加额外的偏移量来确保元素更居中
            const offsetY = (containerRect.height - itemRect.height) / 2;
            const centerPosition = itemRect.top - containerRect.top - offsetY;
            
            // 为了解决滚动偏前的问题，使用scrollTo手动设置位置
            if (Math.abs(centerPosition) > 10) { // 只有当偏差足够大时才调整
              container.scrollTo({
                top: container.scrollTop + centerPosition,
                behavior: 'smooth'
              });
            }
          } catch {
            // 如果出错，使用基本的滚动方式
            activeItemRef.current.scrollIntoView({ 
              behavior: 'smooth', 
              block: 'center'
            });
          }
        }
      }, 800);
      
      return () => clearTimeout(timer);
    }
  }, [localCurrentIndex]);

  // 监听视频播放完毕自动切换选集事件
  useEffect(() => {
    const handleEpisodeChanged = (e: CustomEvent) => {
      const index = e.detail?.index;
      if (index !== undefined && index !== localCurrentIndex) {
        console.log('大屏播放列表接收到选集变更事件，更新选中项:', index);
        setLocalCurrentIndex(index);
        
        // 清除当前可能存在的焦点状态
        if (document.activeElement instanceof HTMLElement) {
          document.activeElement.blur();
        }
      }
    };
    
    window.addEventListener('episodeChanged', handleEpisodeChanged as EventListener);
    
    return () => {
      window.removeEventListener('episodeChanged', handleEpisodeChanged as EventListener);
    };
  }, [localCurrentIndex]);
  
  return (
    <div ref={containerRef} className="relative bg-background-darker shadow-lg w-full h-full overflow-hidden playlist-container border-l border-gray-900 rounded-r-lg">
      <div className="absolute inset-0 flex flex-col">
        <h3 className="text-lg p-3 pb-2 font-semibold flex items-center justify-between text-white flex-shrink-0 bg-gradient-to-r from-background-darker to-background-dark border-b border-gray-800/40">
          <div className="flex items-center">
          <span className="w-1 h-5 bg-accent-primary rounded-sm mr-2"></span>
          播放列表
          <span className="ml-2 text-sm text-gray-400">({playList.length}集)</span>
          </div>
          <button 
            onClick={toggleSort}
            className="p-1 hover:bg-background-hover rounded-md transition-colors"
            title={isReversed ? "正序排列" : "倒序排列"}
          >
            <svg 
              className={`w-5 h-5 text-gray-400 transition-transform ${isReversed ? 'rotate-180' : ''}`} 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path 
                strokeLinecap="round" 
                strokeLinejoin="round" 
                strokeWidth={2} 
                d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12" 
              />
            </svg>
          </button>
        </h3>
        <div ref={scrollContainerRef} className="flex-grow overflow-y-auto px-2.5 custom-scrollbar py-2.5 scrollbar-container">
          <div 
            className="grid gap-2"
            style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}
          >
            {columns === 0 ? (
              <div className="col-span-full flex items-center justify-center py-8">
                <div className="flex items-center text-gray-400">
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  正在加载中...
                </div>
              </div>
            ) : (
              sortedPlayList.map((play, sortedIndex) => {
                // 通过sortedPlayList和playList的关系计算原始索引
                const originalIndex = isReversed ? (playList.length - 1 - sortedIndex) : sortedIndex;
                const isActive = localCurrentIndex === originalIndex;
                
                return (
                  <HtmlLink
                    key={sortedIndex}
                    href={videoId ? `/detail/${videoId}-${originalIndex}.html` : '#'}
                    ref={isActive ? activeItemRef : null}
                    onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
                      e.preventDefault(); // 阻止默认链接跳转行为
                      handleEpisodeClick(originalIndex);
                    }}
                    className={`px-4 py-3 ${
                      isActive 
                        ? 'bg-red-600 hover:bg-red-700'
                        : 'bg-background-card hover:bg-background-hover'
                    } text-white text-sm rounded-md transition truncate text-left flex items-center hover:text-white focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50 ${
                      columns > 1 ? 'justify-center' : ''
                    }`}
                  >
                    <span className="truncate">{play.name}</span>
                  </HtmlLink>
                );
              })
            )}
          </div>
        </div>
      </div>
    </div>
  );
}